<template>
  <div style="margin-top: 16px">
    <el-form-item label="脚本格式">
      <el-input v-model="scriptTaskForm.scriptFormat" clearable @input="updateElementTask()" @change="updateElementTask()" />
    </el-form-item>
    <el-form-item label="脚本类型">
      <el-select v-model="scriptTaskForm.scriptType">
        <el-option label="内联脚本" value="inline" />
        <el-option label="外部资源" value="external" />
      </el-select>
    </el-form-item>
    <el-form-item label="脚本" v-show="scriptTaskForm.scriptType === 'inline'">
      <el-input
        v-model="scriptTaskForm.script"
        type="textarea"
        resize="vertical"
        :autosize="{ minRows: 2, maxRows: 4 }"
        clearable
        @input="updateElementTask()"
        @change="updateElementTask()"
      />
    </el-form-item>
    <el-form-item label="资源地址" v-show="scriptTaskForm.scriptType === 'external'">
      <el-input v-model="scriptTaskForm.resource" clearable @input="updateElementTask()" @change="updateElementTask()" />
    </el-form-item>
    <el-form-item label="结果变量">
      <el-input v-model="scriptTaskForm.resultVariable" clearable @input="updateElementTask()" @change="updateElementTask()" />
    </el-form-item>
  </div>
</template>

<script setup name="ScriptTask">

const {proxy} = getCurrentInstance()

const props = defineProps({
  id: String,
  type: String
})
const {id,type} = toRefs(props)
const state = reactive({
  defaultTaskForm: {
    scriptFormat: "",
    script: "",
    resource: "",
    resultVariable: ""
  },
  scriptTaskForm: {},
  bpmnElement: undefined
})
const {defaultTaskForm,scriptTaskForm} = toRefs(state)

watch(()=>props.id,() => {
  state.bpmnElement = window.bpmnInstances.bpmnElement;
  proxy.$nextTick(() => resetTaskForm());
}, { immediate: true })

function resetTaskForm() {
  for (let key in state.defaultTaskForm) {
    let value = state.bpmnElement?.businessObject[key] || state.defaultTaskForm[key];
    state.scriptTaskForm.key = value
  }
  state.scriptTaskForm.scriptType = state.scriptTaskForm.script ? "inline" : "external"
}
function updateElementTask() {
  let taskAttr = Object.create(null);
  taskAttr.scriptFormat = state.scriptTaskForm.scriptFormat || null;
  taskAttr.resultVariable = state.scriptTaskForm.resultVariable || null;
  if (state.scriptTaskForm.scriptType === "inline") {
    taskAttr.script = state.scriptTaskForm.script || null;
    taskAttr.resource = null;
  } else {
    taskAttr.resource = state.scriptTaskForm.resource || null;
    taskAttr.script = null;
  }
  window.bpmnInstances.modeling.updateProperties(toRaw(state.bpmnElement), taskAttr);
}
onUnmounted(() => {
  state.bpmnElement = null;
})

</script>
